package ua.com.toltec.flymodemanager;

import java.util.GregorianCalendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class ServiceAirplaneMode extends Service {

	int REQUEST_CODE = 11223344;

	AlarmManager alarmManager;
	PreferenceUnit pr;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		pr = new PreferenceUnit(getApplicationContext());
		
		startService();
		Log.v(this.getClass().getName(), "onCreate(..)");
	}

	@Override
	public IBinder onBind(Intent intent) {
		Log.v(this.getClass().getName(), "onBind(..)");
		return null;
	}

	@Override
	public void onDestroy() {
		if (alarmManager != null) {
			Intent intent = new Intent(this, RepeatingAlarmService.class);
			alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE,
					intent, 0));
		}
		Toast.makeText(this, "Service Stopped!", Toast.LENGTH_LONG).show();
		Log.v(this.getClass().getName(),
				"Service onDestroy(). Stop AlarmManager at "
						+ new java.sql.Timestamp(System.currentTimeMillis())
								.toString());
	}

	private void startService() {

		Intent intent = new Intent(this, RepeatingAlarmService.class);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
				REQUEST_CODE, intent, 0);

		if (alarmManager == null) {
			alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

		}

		
		alarmManager.cancel(pendingIntent);
		
		GregorianCalendar calendar = new GregorianCalendar();

		long nextInterval = pr.getNextInterval(calendar);

		alarmManager.set(AlarmManager.RTC_WAKEUP,
				nextInterval,
				pendingIntent);
		
		Log.i("startService", pr.calendar2string(pr.milliseconds2calendar(nextInterval)));
		
//		alarmManager.setRepeating(
//                AlarmManager.ELAPSED_REALTIME_WAKEUP,
//                SystemClock.elapsedRealtime() + 5000,
//                10000,
//                pendingIntent);
//		Toast.makeText(this, "Service Started.", Toast.LENGTH_LONG).show();
	
		Log.v(this.getClass().getName(), "AlarmManger started at "
				+ new java.sql.Timestamp(System.currentTimeMillis()).toString());
	}
}